$(function () {

    inputRadioSel($(".i-checks"),selectChecks);

    onOffSwitchSel($(".onoffswitch"),switchChecks);

    allChickBox($('.i-checks'),selectCall);
    $("body").on("click","#logoImgFile",function () {//LOGO图片上传 (140px * 84px)
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadLogoCallback',
            cut:false//不开启剪切
        });
    }).on("click","#logoImgFileSecond",function () {//LOGO图片上传 (128px * 128px)
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadLogoSecondCallback',
            cut:false//不开启剪切
        });
    }).on('click',"#icoDocuFileBtn",function () {//ICO图片上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'ico',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadIcoCallback',
            cut:false//不开启剪切
        });
    }).on('click','#appDowFileBtn',function () {//App下载二维码上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadAppDowCallback',
            cut:false//不开启剪切
        });
    }).on('click',"#h5MobileAppDowFileBtn",function () {//H5&微信二维码
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadH5WeiXinCallback',
            cut:false//不开启剪切
        });
    }).on('click',"#smallAppDowFileBtn",function () {//小程序二维码上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadSmallAppCallback',
            cut:false//不开启剪切
        });
    }).on("click",'#saveConfig',function () {
        saveConfig();
    }).on("click","#appDUploadBtn",function () {//安卓apk上传
        //初始化apk上传窗口
        initUpdateFileWin({
            fileType:'apk',//文类类型["img","ico","xls","pdf","zip","apk"]
            callback:'apkUploadCallback',
            cut:false//不开启剪切
        });
    }).on('click','#update-version',function () {//更新版本号
        $("input[name='version']").val(new Date().getTime());
    }).on('change','#video-type',function () {//选择服务商
        var type = $(this).val();
        if(type=='CC'){
            $("#cc-server").removeClass('hide');
            $("#isK96keVideo").removeClass('hide');
            $("#tt-server").addClass('hide');
        }else if(type=='TT'){
            $("#tt-server").removeClass('hide');
            $("#cc-server").addClass('hide');
            $("#isK96keVideo").removeClass('hide');
        }
    }).on('change','#iosDeal',function () {
        if($(this).is(':checked')){
            $('input[name="iosWithdraw"]').attr("disabled",false);
            $('input[name="iosIncome"]').attr("disabled",false);
        }else{
            $('input[name="iosWithdraw"]').attr("disabled",true).attr('checked',false);
            $('input[name="iosIncome"]').attr("disabled",true).attr('checked',false);
        }

    }).on("click","input[name='iosWithdraw'],input[name='iosIncome']",function(){
        if(!$("input[name='iosWithdraw']").is(':checked')&&!$("input[name='iosIncome']").is(':checked')){
            $("#iosDeal").attr('checked',false);
            $("input[name='iosWithdraw']").attr("disabled",true);
            $("input[name='iosIncome']").attr("disabled",true);
        }
    }).on('click','.update-msg-type-box',function () {//修改消息通知方式
        var _this = $(this);
        var _vals = _this.data('type');
        var siteChecked = ''
        if(_vals.indexOf('site') !=-1){
            siteChecked = 'checked';
        }
        var wxChecked = '';
        if(_vals.indexOf('wx') !=-1){
            wxChecked = 'checked';
        }
        var context = '<div class="m-t m-r m-l m-b">' +
            '<div class="checkbox"><label><input class="i-checks" '+siteChecked+' type="checkbox" value="site"/> 站内消息</label></div>' +
            '<div class="checkbox"><label><input class="i-checks" '+wxChecked+' type="checkbox" value="wx"/> 微信消息</label></div>' +
            '</div>';
        parent.layer.open({
            type: 1,
            shadeClose: false,
            shade: [0.3, '#000000'],
            title: '<strong>修改消息通知方式</strong>',
            area:  ['400px','180px'],
            content: context,
            btn: ['确认'],
            success:function(layero){
            },
            yes: function (index, layero) {
                var list = layero.find("input:checked");
                if(list.length > 0){
                    var vals = list.map(function () {
                        return this.value;
                    }).get().join(",");
                    var _context = '';
                    if(vals.indexOf('site') != -1){
                        _context +='<span data-type="site" class="btn btn-info btn-xs disabled">站内消息</span>&nbsp;'
                    }
                    if(vals.indexOf('wx') != -1){
                        _context +='<span data-type="wx" class="btn btn-primary btn-xs disabled">微信消息</span>'
                    }
                    _this.parent('div').find('span[data-type]').remove();
                    _this.parent('div').find('input:hidden').val(vals);
                    _this.before(_context);
                    _this.attr('data-type',vals);
                    _this.data('type',vals);
                    parent.layer.close(index);
                }else{
                    icModale(0,'请选择消息通知方式');
                }
            }
        });
    }).on('blur','input[name=refundTime]',function () {
        var reg =/^[1-9]+[0-9]*$/;
        var refundTime = $(this).val();
        if(!reg.test(refundTime)){
            $(this).val(1);
        }
    }).on("click","#wechatServiceBtn",function () {//LOGO图片上传 (128px * 128px)
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadWechatServicCallback',
            cut:false//不开启剪切
        });
    })

    /**
     * 开关按钮对象改变时触发方法
     * @param em
     */
    function switchChecks(em) {
        if (em.name == 'statisticsOnOffSwitch'){
            if (em.checked){
                $('.selectStatistics').removeClass('hide');
                $('.mateParams').removeClass('hide');
                $('.showCode').removeClass('hide');
            }
            if (!em.checked){
                $('.selectStatistics').addClass('hide');
                $('.mateParams').addClass('hide');
                $('.showCode').addClass('hide');
            }
        }
    }

    /**
     * 选择被选中的按钮对象
     * @param em
     */
    function selectChecks(em){
        if(em.name == 'statisticsSwitch'){
            var statisticsId = $('#statisticsId').val();
            var mateCodeId = $('#mateCodeId').val();
            if(em.value == 1){
                $('.baiduConfig').removeClass('hide');
                $('.tencentConfig').addClass('hide');
                $('.cnzzConfig').addClass('hide');
                $('.googleConfig').addClass('hide');
                $('.mateText').html('hm.src = ');
                if(statisticsId != 1){
                    $("input[name='matecode']").val('');
                }else{
                    $("input[name='matecode']").val(mateCodeId);
                }
                $("input[name='matecode']").attr('placeholder','请输入百度统计配置参数');
            }
            if(em.value == 2){
                $('.baiduConfig').addClass('hide');
                $('.tencentConfig').removeClass('hide');
                $('.cnzzConfig').addClass('hide');
                $('.googleConfig').addClass('hide');
                $('.mateText').html('sId = ');
                if(statisticsId != 2){
                    $("input[name='matecode']").val('');
                }else{
                    $("input[name='matecode']").val(mateCodeId);
                }
                $("input[name='matecode']").attr('placeholder','请输入腾讯分析配置参数');
            }
            if(em.value == 3){
                $('.baiduConfig').addClass('hide');
                $('.tencentConfig').addClass('hide');
                $('.cnzzConfig').removeClass('hide');
                $('.googleConfig').addClass('hide');
                $('.mateText').html('id = ');
                if(statisticsId != 3){
                    $("input[name='matecode']").val('');
                }else{
                    $("input[name='matecode']").val(mateCodeId);
                }
                $("input[name='matecode']").attr('placeholder','请输入CNZZ配置参数');
            }
            if(em.value == 4){
                $('.baiduConfig').addClass('hide');
                $('.tencentConfig').addClass('hide');
                $('.cnzzConfig').addClass('hide');
                $('.googleConfig').removeClass('hide');
                $('.mateText').html('UA- = ');
                if(statisticsId != 4){
                    $("input[name='matecode']").val('');
                }else{
                    $("input[name='matecode']").val(mateCodeId);
                }
                $("input[name='matecode']").attr('placeholder','请输入谷歌分析配置参数');
            }
        }
        if (em.name == 'anUrlRadio'){
            if (em.value == "nativeUrl"){
                $('.nativeUrl').removeClass('hide');
                $('.appStoreUrl').addClass('hide');
                $("._anUrl2").removeClass('hide');
                $("._anUrl2").removeAttr('disabled');
                $("._anUrl1").attr("disabled",true);
                $("._anUrl1").addClass('hide');
                $(".startStatus").removeClass('hide');
            }
            if (em.value == "appStoreUrl"){
                $('.nativeUrl').addClass('hide');
                $('.appStoreUrl').removeClass('hide');
                $("._anUrl2").addClass('hide');
                $("._anUrl2").attr("disabled",true);
                $("._anUrl1").removeAttr('disabled');
                $("._anUrl1").removeClass('hide');
                $(".startStatus").removeClass('hide');
            }
        }
    }

    /**
     * 保存配置信息
     */
    function saveConfig() {
        var params = $("#sysConfigForm").serializeJSON();
        if($("input[name='configType']").val()=="INFO"){
            var _copyright1 = $("._copyright1").val();
            var _copyright2 = $("._copyright2").val();
            var _copyright3 = $("._copyright3").val();
            _copyright3 =   '<a href="http://beian.miit.gov.cn">'+_copyright3+'</a>';
            var copyright = _copyright1+'-{year}'+_copyright2+_copyright3;
            params.copyright = copyright;
        }
        if($("input[name='configType']").val()=="V96K"){
            params.concurrentLive = $("input[name='concurrentLive']").val();
            params.personTimeLive =$("input[name='personTimeLive']").val();
            params.interactiveLive = $("input[name='interactiveLive']").val();
        }
        if($("input[name='configType']").val()=="COUNTCODE"){
            //页面初始数据
            var _mateCode = $('#mateCodeId').val();
            var _statisticsSwitch = $('#statisticsId').val();
            //页面获取最新数据
            var matecode = $("input[name='matecode']").val();
            var codeList = $("textarea[name='code']");
            var code = '';
            $.each(codeList,function (i,e) {
                if (!$(e).hasClass('hide')) {
                    code = $(e).val();
                }
            });
            //改变统计商并且统计开关关闭
            if (_statisticsSwitch != params.statisticsSwitch && params.statisticsOnOffSwitch == undefined) {
                params.matecode = _mateCode;
                params.statisticsSwitch = _statisticsSwitch;
            }
            code = code.replace('参数配置',matecode);
            params.code = code;
        }

        params = JSON.stringify(params);
        $.ajax({
            url: baseloaction + '/admin/manage/config/saveConfig',
            type:"post",
            dataType:'json',
            data:params,
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                if(result.success==true){
                    var funType = $("#funType").val();
                    window.location.href= baseloaction + '/admin/manage/config/configList?funType='+funType
                }else{
                    icModale(0, result.message);
                }
            },
            error:function (error) {
                icModale(0, "系统错误，配置数据保存失败");
            }
        });
    }

    //初始化编辑框
    initSNU({
        id:'protocol-context',
        type:1,
        toolsArr:null,
        height:360,
        gs:true,
        video:true
    });

    function allChickBox(str, selectCall) {
        $(str).on("ifClicked", function (event) {
            selectCall(event.target);
        });
    }
});

/**
 * 上传App二维码图片回调
 * @param data
 */
function uploadAppDowCallback(data) {
    $("#app-img").parent().removeClass("hide");
    $("#appUrl").val(data.url);
    $("#app-img").attr("src",data.url);
}
/**
 * 上传H5&微信二维码图片回调
 * @param data
 */
function uploadH5WeiXinCallback(data) {
    $("#hMobileImage").parent().removeClass("hide");
    $("#hmUrl").val(data.url);
    $("#hMobileImage").attr("src",data.url);
}

/**
 * 上传微信小程序码回调
 */
function uploadSmallAppCallback(data) {
    $("#smallAppImage").parent().removeClass("hide");
    $("#smallAppUrl").val(data.url);
    $("#smallAppImage").attr("src",data.url);
}

/**
 * 安卓更新包上传回调
 * @param data
 */
function apkUploadCallback(data){
    if(data.fileName!=null&&data.savePath!= null && data.url != null){
        $("._anUrl2").val(data.url);//上传成功后把下载地址传到前台
        icModale(0,"apk上传成功");
    }else{
        icModale(0,"apk上传失败");
    }
}

/**
 * 上传ico回调
 * @param data
 */
function uploadIcoCallback(data) {
    $("#ico-img").attr('src',data.url);
    $("#icoUrl").val(data.url);
}

/**
 * 上传Logo回调
 * @param data
 */
function uploadLogoCallback(data) {
    $("#logo-img").parent().removeClass("hide");
    $("#logoUrl").val(data.url);
    $("#logo-img").attr("src",data.url);
}

/**
 * 上传Logo回调
 * @param data
 */
function uploadLogoSecondCallback(data) {
    $("#logo-second-img").parent().removeClass("hide");
    $("#logoUrlSecond").val(data.url);
    $("#logo-second-img").attr("src",data.url);
}

/**
 * 上传Logo回调
 * @param data
 */
function uploadWechatServicCallback(data) {
    $("#wechatService-img").parent().removeClass("hide");
    $("#wechatServiceUrl").val(data.url);
    $("#wechatService-img").attr("src",data.url);
}

function selectCall(em) {
    var name = em.name;
    if(name=="concurrentLive") {
        var tb1 = $(document.getElementById('concurrentLive'));
        if (em.checked == false) {//未选中
            tb1.removeClass('hide');
            $("input[name='concurrentLive']").val(true);
        } else {//选中
            tb1.addClass('hide');
            $("input[name='concurrentLive']").val(false);
            tb1.find('.auth_id').val("");
            tb1.find('.auth_key').val("");
        }
    }

    if(name=="personTimeLive") {
        var tb1 = $(document.getElementById('personTimeLive'));
        if (em.checked == false) {//未选中
            $("input[name='personTimeLive']").val(true);
            tb1.removeClass('hide');
        } else {//选中
            $("input[name='personTimeLive']").val(false);
            tb1.addClass('hide');
            tb1.find('.auth_id').val("");
            tb1.find('.auth_key').val("");
        }
    }

    if(name=="interactiveLive") {
        var tb1 = $(document.getElementById('interactiveLive'));
        if (em.checked == false) {//未选中
            $("input[name='interactiveLive']").val(true);
            tb1.removeClass('hide');
        } else {//选中
            $("input[name='interactiveLive']").val(false);
            tb1.addClass('hide');
            tb1.find('.auth_id').val("");
            tb1.find('.auth_key').val("");
        }
    }
}